<!-- eslint-disable unicorn/prefer-ternary -->
<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { h, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  autoSort,
  sysDeptList,
  sysDeptRemove,
  updateSort,
} from '#/api/sys/dept';
import { TableAction } from '#/components/table-action';
import { getChildIds } from '#/util/tool';

import DetailForm from './detail.vue';
import DeptForm from './form.vue';
import { gridSchemas } from './schemas';

const hasTopTableDropDownActions = ref(false);
const deptFormRef = ref();
const detailFormRef = ref();
const isExpand = ref(false);
const originalData = ref<any[]>([]);
const expandRowKeys = ref<string[]>([]);
const gridOptions: VxeGridProps<any> = {
  ...gridSchemas,
  toolbarConfig: {
    ...gridSchemas.toolbarConfig,
    slots: {
      buttons: 'toolbar-buttons',
    },
    custom: {
      // 自定义列-图标
      icon: 'vxe-icon-menu',
    },
    refresh: {
      queryMethod: () => {
        reload();
      },
    },
  },
  border: false,
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
  rowConfig: {
    drag: true,
  },
  rowDragConfig: {
    isPeerDrag: true,
    dragEndMethod: (params) => {
      const oldSort = params.oldRow.sort;
      const newSort = params.newRow.sort;
      gridApi.grid.setRow([params.newRow], {
        sort: oldSort,
      });
      gridApi.grid.setRow([params.oldRow], {
        sort: newSort,
      });
      return new Promise((resolve) => {
        gridApi.setState({
          gridOptions: {
            loading: true,
          },
        });
        updateSort([
          {
            id: params.newRow.id,
            sort: oldSort,
          },
          {
            id: params.oldRow.id,
            sort: newSort,
          },
        ])
          .then(() => {
            message.success('更新排序成功');
            resolve(true);
          })
          .catch(() => {
            resolve(false);
          })
          .finally(() => {
            gridApi.setState({
              gridOptions: {
                loading: false,
              },
            });
          });
      });
    },
  },
  treeConfig: {
    transform: true,
    rowField: 'id',
    parentField: 'parentId',
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        originalData.value = await sysDeptList({});
        return originalData.value;
      },
    },
    response: {
      list: '',
    },
  },
};
const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  toggleTreeExpand() {
    if (gridApi.grid.getTreeExpandRecords().length === 0) {
      // 已全部折叠，则设置成可展开
      isExpand.value = false;
    }
  },
};
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents,
});
// 重新设置展开行keys-临时保存，非真实设置
const resetExpandRowKeys = () => {
  expandRowKeys.value = gridApi.grid
    .getTreeExpandRecords()
    ?.map((item) => item.id);
};
/**
 * 自定义刷新方法
 */
const reload = () => {
  resetExpandRowKeys();
  gridApi.reload().then(() => {
    if (expandRowKeys.value.length > 0) {
      const records = originalData.value.filter((item) =>
        expandRowKeys.value.includes(item.id),
      );
      gridApi.grid.setTreeExpand(records, true);
    }
  });
};
// 打开新增表单
const handleAdd = (record: any) => {
  deptFormRef.value.setData({
    record,
    isUpdate: false,
    gridApi: {
      ...gridApi,
      reload,
      resetExpandRowKeys,
    },
  });
  deptFormRef.value.open();
};
// 打开编辑表单
const handleEdit = (record: any) => {
  deptFormRef.value.setData({
    record,
    isUpdate: true,
    gridApi: {
      ...gridApi,
      reload,
      resetExpandRowKeys,
    },
  });
  deptFormRef.value.open();
};
// 打开详情
const handleDetail = (record: any) => {
  detailFormRef.value.setData({
    record,
  });
  detailFormRef.value.open();
};
// 删除
const handleDelete = (row: any) => {
  resetExpandRowKeys();
  const ids = [];
  if (row) {
    ids.push(...getChildIds(row));
  }
  sysDeptRemove({ ids }).then(() => {
    message.success('删除成功');
    reload();
  });
};
/**
 * 展开/折叠
 */
const handleExpandAndCollapse = () => {
  if (isExpand.value) {
    gridApi.grid.setAllTreeExpand(false);
    isExpand.value = false;
  } else {
    gridApi.grid.setAllTreeExpand(true);
    isExpand.value = true;
  }
};
// 自动调整排序
const handleReSort = (): any => {
  resetExpandRowKeys();
  return new Promise<boolean>((resolve, reject) => {
    autoSort({})
      .then(() => {
        message.success('重排序成功');
        resolve(true);
        reload();
      })
      .catch(reject);
  });
};
const handleDisabled = (
  row: any,
  seq: string,
  type: 'down' | 'up',
): boolean => {
  if (!seq) return false;

  // 分割 seq 获取层级信息（如 "1.2.3" => ["1", "2", "3"]）
  const seqParts = seq.split('.');

  if (seqParts.length === 1) {
    // 顶级节点（如 "1", "2"）
    const totalTopLevel = originalData.value.filter(
      (item) => item.parentId === '0',
    ).length;
    const currentIndex = Number(seqParts[0]);

    if (type === 'up') {
      return currentIndex === 1; // 第一个顶级节点不能上移
    } else {
      return currentIndex === totalTopLevel; // 最后一个顶级节点不能下移
    }
  } else {
    // 子级节点（如 "1.1", "1.2.1"）
    const parentId = row.parentId;
    const siblings = originalData.value
      .filter((item) => item.parentId === parentId)
      .sort((a, b) => a.sort - b.sort); // 按 sort 排序

    const seqLastPart = Number(seqParts[seqParts.length - 1]);

    if (type === 'up') {
      return seqLastPart === 1; // 同级第一个不能上移
    } else {
      return seqLastPart === siblings.length; // 同级最后一个不能下移
    }
  }
};
const handleMoveRowTo = (row: any, offset: number) => {
  gridApi.grid.moveRowTo(row, offset);
};
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              auth: ['admin', 'sys:dept:save'],
              onClick: handleAdd.bind(null, {}),
            },
            {
              label: isExpand ? '折叠' : '展开',
              type: 'primary',
              icon: isExpand
                ? 'ant-design:menu-fold-outlined'
                : 'ant-design:menu-unfold-outlined',
              onClick: handleExpandAndCollapse.bind(null),
            },
            {
              label: '自动调整排序',
              danger: true,
              type: 'dashed',
              icon: 'ant-design:sort-ascending-outlined',
              auth: ['admin', 'sys:dept:autoSort'],
              confirm: {
                icon: 'warning',
                title: '自动调整排序规则',
                content: h(
                  'div',
                  {
                    class: 'text-center space-y-3 px-4 py-3', // 增加间距和内边距
                  },
                  [
                    h(
                      'div',
                      { class: 'text-gray-600 text-left' }, // 左对齐规则列表
                      [
                        h('ol', { class: 'list-decimal pl-5 space-y-2' }, [
                          h('li', '层级越深，排序值越大'),
                          h('li', '同级节点之间间隔至少 1000'),
                          h('li', '不同层级之间间隔为 10000'),
                        ]),
                      ],
                    ),
                    h(
                      'div',
                      { class: 'text-red-500 font-medium' },
                      '确定要执行自动调整排序吗？',
                    ), // 强调确认问题
                  ],
                ),
                beforeClose({ isConfirm }) {
                  if (isConfirm) {
                    // 这里可以执行一些异步操作。如果最终返回了false，将阻止关闭弹窗
                    return handleReSort();
                  }
                },
              },
            },
          ]"
        />
      </template>
      <template #toolbar-tools></template>
      <template #ACTION="{ row, seq }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              size: 'small',
              auth: ['admin', 'sys:dept:detail'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: '编辑',
              type: 'link',
              size: 'small',

              auth: ['admin', 'sys:dept:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: '上移',
              type: 'link',
              size: 'small',
              auth: ['admin', 'sys:dept:updateSort'],
              disabled: handleDisabled(row, seq, 'up'),
              onClick: handleMoveRowTo.bind(null, row, -1),
            },
            {
              label: '下移',
              type: 'link',
              size: 'small',
              auth: ['admin', 'sys:dept:updateSort'],
              disabled: handleDisabled(row, seq, 'down'),
              onClick: handleMoveRowTo.bind(null, row, 1),
            },
          ]"
          :drop-down-actions="[
            {
              label: '添加下级',
              type: 'link',
              icon: 'ant-design:plus-outlined',
              size: 'small',
              auth: ['admin', 'sys:dept:save'],
              onClick: handleAdd.bind(null, {
                parentId: row.id,
              }),
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              auth: ['admin', 'sys:dept:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
    <DeptForm ref="deptFormRef" />
    <DetailForm ref="detailFormRef" />
  </Page>
</template>
